#include "stdafx.h"

void processElement(int i, int j, int k)
{
	double v_old = matrix[i][j][s];
	double v_new = k2*(matrix[i][j+1][s] + matrix[i][j-1][s]) + h2*(matrix[i+1][j][s] + matrix[i-1][j][s]) + l2*(matrix[i][j][s+1] + matrix[i][j][s-1]) - f[i][j][s];
	v_new = v_new / a2;
	eps_cur = fabs(v_old - v_new);
	if (eps_cur > eps_max)
		eps_max = eps_cur;
	matrix[i][j][s] = v_new;
}

bool flag = false;
double h2 = size_x*size_x/(b-a)/(b-a);
double k2 = size_y*size_y/(d-c)/(d-c);
double l2 = size_z*size_z/(q-p)/(q-p);
double a2 = 2 * (h2 + k2);

double eps_max = 0;
double eps_cur = 0;
int steps = 0;

while (!flag)
{
	eps_max = 0;
	// bread
	for (int s=1; s<size_z/2; s++)
		for (int j=1; j<size_y; j++ )
			for (int i=1; i<size_x; i++)
				processElement(i, j, s)
	
	// butter and sausage
	for (int s=size_z/2; s<size_z; s++)
	{
		for (int i=1; i<size_x/2; i++)
			for (int j=1; j<size_y; j++ )
				processElement(i, j, s);
		for (int i=size_x/2; i<size_x; i++)
			for (int j=size_y/2; j<size_y; j++ )
				processElement(i, j, s);
	}
	steps++;
	if ((eps_max < accuracy) || (steps >= num_steps)) 
		flag = true;
}